from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from backend.common.database import Base
from .base_model import BaseModel


class User(BaseModel):
    __tablename__ = "user"  # 数据库表名
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True, comment="主键ID")
    username = Column(String(20), nullable=False, unique=True, comment="用户姓名")
    password = Column(String(128), nullable=False, comment="密码")  # 增加密码长度
    nickname = Column(String(50), nullable=True, comment="昵称")
    email = Column(String(100), nullable=True, comment="电子邮箱")  # 增加电子邮箱长度

    roles = relationship('Role', secondary='user_roles', back_populates='users')  # 使用中间表


class Role(Base):
    __tablename__ = 'role'
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, index=True, comment="角色名称")  # 指定长度并添加注释

    permissions = relationship('Permission', secondary='role_permissions', back_populates='roles')  # 使用中间表
    users = relationship('User', secondary='user_roles', back_populates='roles')  # 使用中间表


class Permission(Base):
    __tablename__ = 'permission'
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, index=True, comment="权限名称")  # 指定长度并添加注释
    path = Column(String(200), unique=True, comment="权限路径")

    roles = relationship('Role', secondary='role_permissions', back_populates='permissions')  # 使用中间表


# 中间表定义：用户与角色之间的多对多关系
class UserRole(Base):
    __tablename__ = 'user_roles'

    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    role_id = Column(Integer, ForeignKey('role.id'), primary_key=True)


# 中间表定义：角色与权限之间的多对多关系
class RolePermission(Base):
    __tablename__ = 'role_permissions'

    role_id = Column(Integer, ForeignKey('role.id'), primary_key=True)
    permission_id = Column(Integer, ForeignKey('permission.id'), primary_key=True)